package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("friend")
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserClient userClient;
    @Autowired
    private NoFriendService noFriendService;
    //1.添加好友
    @PutMapping("like/{friendid}/{type}")
    public Result add(@PathVariable String friendid,@PathVariable String type){
        //1.1 从请求作用域中得到claims
        Claims claims = (Claims) request.getAttribute("claims");
        System.out.println("claims:" + claims);
        //1.2 判断是否有值，且roles是否为user
        if (claims != null){
            String roles = claims.get("roles") + "";
            if (!roles.equals("user")){
                return new Result(false,StatusCode.REPERROR,"无权访问");
            }
            //1.3 如果roles为user，则添加好友
            if (type.equals("1")){
                int count = friendService.add(claims.getId().toString(),friendid);
                if (count == 0){
                    return new Result(false,StatusCode.REPERROR,"重复添加好友！");
                }
              //1.4 更新粉丝数以及关注数
                userClient.incFans(friendid,1);
                userClient.incfollow(claims.getId(),1);
            }else {
             noFriendService.add(claims.getId(),friendid);
            }
        }
        return new Result(true,StatusCode.OK,"添加好友成功");
    }
    //2 删除好友
    @DeleteMapping("{friendid}")
    public Result dele(@PathVariable String friendid){
        //2.1. c从request作用域中得到claims
        Claims claims = (Claims) request.getAttribute("claims");
        //2.2 如果claims不为空，就得到roles
        if (claims != null){
            String roles = (String) claims.get("roles");
            //2.3 如果claims有值就可以删除
            if (roles != null ){
                friendService.dele(claims.getId(),friendid);
                userClient.incfollow(claims.getId(),-1);
                userClient.incFans(friendid,-1);
                return new Result(true,StatusCode.OK,"删除好友成功");
            }
        }
        return new Result(false,StatusCode.REPERROR,"权限不足");
    }
}
